﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MyServer.Common;
using System.Net;
using System.Net.Sockets;

namespace MyServer.Udp
{
    /// <summary>
    /// 表示一个基于Udp协议的收发中心
    /// </summary>
    public class UdpCenter:DataCenterBase
    {

        /// <summary>
        /// 通过指定的本地终结点初始化Udp收发中心实例
        /// </summary>
        /// <param name="LoaclPoint">与Udp收发中心关联的本地终结点</param>
        public UdpCenter(DataOperatorBase oper = null)
        {
            this.ConnectionManager = new UdpConnectManager(this);
            this.Listener = new UdpDataListener(this);
            this.Reader = new UdpDataReader(this);
            this.Sender = new UdpDataSender(this);

            if (oper == null)
                this.Operator = new UdpOperator(this);
            else
                this.Operator = oper;

        }

        protected override void DataListener_DataAvailable(object sender,DataListenerEventArgs e)
        {
            UdpClient client =(UdpClient)e.Connect;
            IPEndPoint ep=new IPEndPoint(IPAddress.Any,0);
            UdpPkgInfo Info = new UdpPkgInfo(client, ep);
            e.Data.Tag = Info;
            base.DataListener_DataAvailable(sender,e);
        }

        public override bool Start()
        {
            return base.Start();
        }

        /// <summary>
        /// 发送数据到指定远端
        /// </summary>
        /// <param name="LocalClient">本地Udp客户端实例</param>
        /// <param name="RemotePoint">目标远端地址</param>
        /// <param name="Data">要发送的数据</param>
        /// <param name="pkgName">数据包名称</param>
        /// <param name="IsRecive">是否加入接收监听队列</param>
        public void SendTo(UdpClient LocalClient,IPEndPoint RemotePoint,byte[] Data,string pkgName,bool IsRecive=false)
        {
                DataPackageCollection pkg = DataPacker.PackData(Data, pkgName);
                UdpPkgInfo Info = new UdpPkgInfo(LocalClient, RemotePoint);
                pkg.Tag =Info;
                Sender.AddToQueue(pkg);
                if (IsRecive)
                {
                    Listener.AddConnect(LocalClient);
                }
        }

    }
}
